<?php

namespace app\admin\controller;
use app\common\controller\Admin;
use app\api\model\PetsDiary;

class Diary extends Admin
{
    public function index() {
        $map = array();

		$order = "id desc";
		$list  = PetsDiary::with(['pets', 'user'])->where($map)->order($order)->paginate(10);

		$data = array(
			'list' => $list,
			'page' => $list->render(),
		);
		$this->assign($data);
		$this->setMeta("宠物日记");
        return $this->fetch();
    }

    public function delete($id = 0) {
		if (!$id) {
			return $this->error("非法操作！", '');
		}
		$map['id'] = array('IN', $id);
		$result    = db('PetsDiary')->where($map)->delete();
		if ($result) {
			action_log('delete_action', 'PetsDiary', $id, session('user_auth.uid'));
			return $this->success('删除成功！');
		} else {
			return $this->error('删除失败！');
		}
    }

    public function edit($id = null) {
		$model = model('PetsDiary');
		if (request()->isPost()) {
            $data = input('post.');
			$result = $model->save($data, ['id' => $id]);
			if ($result) {
				return $this->success("修改成功！", url('admin/diary/index'));
			} else {
				return $this->error($model->getError());
			}
		} else {
			$info = $model->where(array('id' => $id))->find();
			if (!$info) {
				return $this->error("非法操作！");
			}
			$data = array(
				'info'    => $info,
				'keyList' => $model->keyList,
			);
			$this->assign($data);
			$this->setMeta("编辑宠物日记");
			return $this->fetch('public/edit');
		}
	}
}
